package cn.kgc.vue.controller;

import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Permission;
import cn.kgc.vue.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * @author 课工场
 * @date 2023/12/9
 * @description  权限控制层
 */

@Api(tags = "权限模块")
@RestController
@RequestMapping("permissions")
public class PermissionController {

    @Resource
    private PermissionService permissionService;
    @ApiOperation("权限列表")
    @GetMapping
    public ResponseResult permissionList(){

        List<Permission> list = permissionService.list();
        return ResponseResult.success().data(list);
    }

    @ApiOperation("根据权限id查询权限信息")
    @GetMapping("{pid}")
    public ResponseResult getPermissionById(@PathVariable Integer pid){

        Permission permission = permissionService.getById(pid);
        Integer pid1 = permission.getPid();
        String parentTitle = "";
        if (pid1!=0){
            parentTitle = permissionService.getById(pid1).getTitle();
        }

        HashMap<String, Object> result = new HashMap<>();
        result.put("permission",permission);
        result.put("parentTitle",parentTitle);

        return ResponseResult.success().data(result);
    }

    @ApiOperation("权限列表")
    @GetMapping("search")
    public ResponseResult permissionList(String title){

        LambdaQueryWrapper<Permission> lambda = new QueryWrapper<Permission>().lambda();
        lambda.eq(Permission::getTitle,title);
        List<Permission> list = permissionService.list(lambda);

        return ResponseResult.success().data(list);
    }


    @ApiOperation("添加/修改列表")
    @PostMapping("saveOrUpdate")
    public ResponseResult permissionList(@RequestBody Permission permission){
        permissionService.saveOrUpdate(permission);

        return ResponseResult.success();
    }


    @ApiOperation("根据权限id删除权限信息")
    @DeleteMapping("{pid}")
    public ResponseResult removePermissionById(@PathVariable Integer pid){

        // 判定删除的权限是否含有子权限
        LambdaQueryWrapper<Permission> lambda = new QueryWrapper<Permission>().lambda();
        lambda.eq(Permission::getPid,pid);
        List<Permission> list = permissionService.list(lambda);
        if (list.size()>0){
            return  ResponseResult.fail().message("不能删除含有子权限的菜单");
        }

        permissionService.removeById(pid);
        return ResponseResult.success().message("删除成功");
    }

}
